package com.example.androidservicetutorial.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;

public class MessengerService extends Service {
    public static final int MSG_SAY_HELLO = 1;
    private final String TAG = getClass().getSimpleName();
    final Messenger messenger = new Messenger(new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case MSG_SAY_HELLO:
                    Log.i(TAG, "thanks,Service had receiver message from client!");
                    //回复客户端信息,该对象由客户端传递过来
                    Bundle bundle1 = msg.getData();
                    String name = bundle1.getString("name");
                    Log.e("name",name);
                    Messenger client = msg.replyTo;
                    Message replyMsg = Message.obtain(null,MessengerService.MSG_SAY_HELLO);
                    Bundle bundle = new Bundle();
                    bundle.putString("reply","ok~,I had receiver message from you!");
                    replyMsg.setData(bundle);
                    try {
                        client.send(replyMsg);
                        Log.e("aaa","aaa");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
            }
            return true;
        }
    }));
    public MessengerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG,"Service is invoke onBind");
        return messenger.getBinder();
    }
}